package com.sghj.utils.okhttp;

import com.burgstaller.okhttp.AuthenticationCacheInterceptor;
import com.burgstaller.okhttp.CachingAuthenticatorDecorator;
import com.burgstaller.okhttp.digest.CachingAuthenticator;
import com.burgstaller.okhttp.digest.Credentials;
import com.burgstaller.okhttp.digest.DigestAuthenticator;
import okhttp3.OkHttpClient;

import javax.net.ssl.*;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.concurrent.ConcurrentHashMap;

public class OkHttpUtils {

    private static OkHttpClient TRUST_ALL_HTTPS_CLIENT = null;

    static {
        try {
            TrustManager[] trustAllCerts = new TrustManager[]{
                    new X509TrustManager() {
                        @Override
                        public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {

                        }

                        @Override
                        public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {

                        }

                        @Override
                        public X509Certificate[] getAcceptedIssuers() {
                            return new X509Certificate[0];
                        }
                    }
            };

            //初始化SSLContext
            SSLContext sc = SSLContext.getInstance("SSL");
            sc.init(null,trustAllCerts,new java.security.SecureRandom());

            //创建一个HostnameVerifier，接受所有主机名
            HostnameVerifier allHostValid = new HostnameVerifier(){

                @Override
                public boolean verify(String s, SSLSession sslSession) {
                    return true;
                }
            };

            final DigestAuthenticator authenticator = new DigestAuthenticator(new Credentials("yf5s-xrx", "Xing..1998"));

            final ConcurrentHashMap<String, CachingAuthenticator> authCache = new ConcurrentHashMap<>();

            TRUST_ALL_HTTPS_CLIENT = new OkHttpClient.Builder()
                    .authenticator(new CachingAuthenticatorDecorator(authenticator, authCache))
                    .addInterceptor(new AuthenticationCacheInterceptor(authCache))
                    .sslSocketFactory(sc.getSocketFactory(),(X509TrustManager) trustAllCerts[0])
                    .hostnameVerifier(allHostValid)
                    .build();

        }catch (Exception e){

        }
    }

    public static OkHttpClient getTrustAllHttpsClient(){
        return TRUST_ALL_HTTPS_CLIENT;
    }
}
